<template>
  <div>
    <div class="header" v-if="showHeader">
      <div class="header-content" :style="{ width: proxy.globalInfo.bodyWidth + 'px' }">
        <!--logo-->
        <div class="logo">悬壶坛</div>
        <!--板块信息-->
        <div class="menu-panel">
          <router-link
            :class="[
            'menu-item home',
            activePboardId == undefined ? 'active' : '',
            ]"
            to="/forum"
          >主坛</router-link>
          <template v-for="board in boardList">
            <el-popover
              placement="bottom-start"
              :width="300"
              trigger="hover"
              v-if="board.children.length &gt; 0"
              :key="board.boardId"
            >
              <template #reference>
                <span
                  :class="[
                    'menu-item',
                    board.boardId == activePboardId ? 'active' : '',
                  ]"
                  @click="boardClickHandler(board)">
                    {{ board.boardName }}
                </span>
              </template>
              <div class="sub-board-list">
                <span
                  :class="[
                    'sub-board',
                    subBoard.boardId == activeBoardId ? 'active' : '',
                  ]"
                  v-for="subBoard in board.children"
                  @click="subBoardClickHandler(subBoard)"
                  :key="subBoard.boardId"
                >
                  {{ subBoard.boardName }}
                </span>
              </div>
            </el-popover>
            <span
              :class="[
                'menu-item',
                board.boardId == activePboardId ? 'active' : '',
              ]"
              v-else
              @click="boardClickHandler(board)"
              :key="board.boardName"
            >{{ board.boardName }}</span>
          </template>
        </div>
        <!--登录，注册 用户信息-->
        <div class="user-info">
          <el-button type="primary" class="color-button" @click="newPost">
            发帖 
            <el-icon style="margin-left: 5px; font-weight: bold;"><Plus /></el-icon>
          </el-button>
          <el-button type="primary" class="color-button" @click="goSearch">
            搜索 
            <el-icon style="margin-left: 5px; font-weight: bold;"><Search /></el-icon>
          </el-button>
          <!--显示用户信息-->
          <template v-if="userInfo.userId">
            <div class="message-info">
              <el-dropdown>
                <el-badge
                  :value="messageCountInfo.total"
                  class="item"
                  :hidden="
                    messageCountInfo.total == null ||
                    messageCountInfo.total == 0
                  "
                >
                  <div class="iconfont icon-message" style="color: #fff;"></div>
                </el-badge>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      @click="gotoMessage('reply')"
                      class="message-item"
                    >
                      <span class="text">回复我的</span>
                        <span
                          class="count-tag"
                          v-if="messageCountInfo.reply &gt; 0"
                        >{{
                          messageCountInfo.reply &gt; 99
                              ? "99+"
                              : messageCountInfo.reply
                        }}</span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="gotoMessage('likePost')"
                      class="message-item"
                    >
                      <span class="text">赞了我的文章</span>
                      <span
                        class="count-tag"
                        v-if="messageCountInfo.likePost &gt; 0"
                      >{{
                        messageCountInfo.likePost &gt; 99
                            ? "99+"
                            : messageCountInfo.likePost
                      }}</span
                            >
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="gotoMessage('downloadAttachment')"
                      class="message-item"
                    >
                      <span class="text">下载了我的附件</span>
                        <span
                          class="count-tag"
                          v-if="messageCountInfo.downloadAttachment &gt; 0"
                        >{{
                          messageCountInfo.downloadAttachment &gt; 99
                              ? "99+"
                              : messageCountInfo.downloadAttachment
                        }}</span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="gotoMessage('likeComment')"
                      class="message-item"
                    >
                      <span class="text">赞了我的评论</span>
                      <span
                        class="count-tag"
                        v-if="messageCountInfo.likeComment &gt; 0"
                      >{{
                        messageCountInfo.likeComment &gt; 99
                            ? "99+"
                            : messageCountInfo.likeComment
                      }}</span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="gotoMessage('sys')"
                      class="message-item"
                    >
                      <span class="text">系统消息</span>
                      <span class="count-tag" v-if="messageCountInfo.sys &gt; 0">
                        {{ messageCountInfo.sys &gt; 99 ? "99+" : messageCountInfo.sys}}
                      </span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="user-info">
              <el-dropdown>
                <avatar
                  :userId="userInfo.userId"
                  :width="50"
                  :addLink="false"
                ></avatar>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="gotoUcenter(userInfo.userId)">
                      我的主页
                    </el-dropdown-item>
                    <el-dropdown-item @click="logout">退出</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <el-button-group class="admin" :style="{ 'margin-left': '10px' }" v-else>
            <el-button type="primary" class="col" plain @click="loginAndRegister(1)">登录</el-button>
            <el-button type="primary" class="col" plain @click="loginAndRegister(0)">注册</el-button>
          </el-button-group>
        </div>
      </div>
    </div>
    <div class="body-content">
      <router-view />
    </div>
    <div class="footer" v-if="showFooter">
      <Footer></Footer>
    </div>
    <!--登录 注册-->
    <LoginAndRegister ref="loginRegisterRef"></LoginAndRegister>
    <!--回到顶部-->
    <el-backtop 
        :right="100" 
        :bottom="100" 
        style="background-color: rgba(0, 0, 0, 0.3); 
        box-shadow: var(--el-box-shadow-lighter);
        text-align: center;
        line-height: 40px;
        color: #91cec9;">
    </el-backtop>
  </div>
</template>

<script setup>
import Footer from '@/components/Footer.vue'
import LoginAndRegister from "./LoginAndRegister.vue";
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const store = useStore();

const api = {
  getUserInfo: "/getUserInfo",
  loadBoard: "/board/loadBoard",
  loadMessageCount: "/ucenter/getMessageCount",
  logout: "/logout",
  getSysSetting: "/getSysSetting",
};

const showHeader = ref(true);

//获取滚动条的高度
const getScrollTop = () => {
  let scrollTop =
    document.documentElement.scrollTop ||
    window.pageYOffset ||
    document.body.scrollTop;
  return scrollTop;
};

const initScroll = () => {
  let initScrollTop = getScrollTop();
  let scrollType = 0;
  window.addEventListener("scroll", () => {
    let currentScrollTop = getScrollTop();
    if (currentScrollTop > initScrollTop) {
      //往下滚动
      scrollType = 1;
    } else {
      //往上滚动
      scrollType = 0;
    }
    initScrollTop = currentScrollTop;
    if (scrollType == 1 && currentScrollTop > 100) {
      showHeader.value = false;
    } else {
      showHeader.value = true;
    }
  });
};

//登录注册
const loginRegisterRef = ref();
const loginAndRegister = (type) => {
  loginRegisterRef.value.showPanel(type);
};

onMounted(() => {
  initScroll();
  getUserInfo();
  loadSysSetting();
});

//获取用户信息
const getUserInfo = async () => {
  let result = await proxy.Request({
    url: api.getUserInfo,
  });
  if (!result) {
    return;
  }
  store.commit("updateLoginUserInfo", result.data);
};

//获取板块信息
const boardList = ref([]);
const loadBoard = async () => {
  let result = await proxy.Request({
    url: api.loadBoard,
  });
  if (!result) {
    return;
  }
  boardList.value = result.data;
  store.commit("saveBoardList", result.data);
};
loadBoard();

//监听 登录用户信息
const userInfo = ref({});
watch(
  () => store.state.loginUserInfo,
  (newVal, oldVal) => {
    if (newVal != undefined && newVal != null) {
      userInfo.value = newVal;
    } else {
      userInfo.value = {};
    }
  },
  { immediate: true, deep: true }
);
//监听是否展示登录框
watch(
  () => store.state.showLogin,
  (newVal, oldVal) => {
    if (newVal) {
      loginAndRegister(1);
    }
  },
  { immediate: true, deep: true }
);

//板块点击
const boardClickHandler = (board) => {
  router.push(`/forum/${board.boardId}`);
};

//二级板块
const subBoardClickHandler = (subBoard) => {
  router.push(`/forum/${subBoard.pBoardId}/${subBoard.boardId}`);
};

//当前选中的板块
const activePboardId = ref(0);
watch(
  () => store.state.activePboardId,
  (newVal, oldVal) => {
    if (newVal !== 0) {
      activePboardId.value = newVal;
    }
  },
  { immediate: true, deep: true }
);

const activeBoardId = ref(0);
watch(
  () => store.state.activeBoardId,
  (newVal, oldVal) => {
    activeBoardId.value = newVal;
  },
  { immediate: true, deep: true }
);

//发帖
const newPost = () => {
  if (!store.getters.getLoginUserInfo) {
    loginAndRegister(1);
  } else {
    router.push("/newPost");
  }
};

const gotoUcenter = (userId) => {
  router.push(`/user/${userId}`);
};

//消息相关
const gotoMessage = (type) => {
  router.push(`/user/message/${type}`);
};

const messageCountInfo = ref({});
const loadMessageCount = async () => {
  let result = await proxy.Request({
    url: api.loadMessageCount,
  });
  if (!result) {
    return;
  }
  messageCountInfo.value = result.data;
  store.commit("updateMessageCountInfo", result.data);
};

watch(
  () => store.state.messageCountInfo,
  (newVal, oldVal) => {
    messageCountInfo.value = newVal || {};
  },
  { immediate: true, deep: true }
);

watch(
  () => store.state.loginUserInfo,
  (newVal, oldVal) => {
    if (newVal) {
      loadMessageCount();
    }
  },
  { immediate: true, deep: true }
);

//退出
const logout = () => {
  proxy.Confirm("确定要退出吗?", async () => {
    let result = await proxy.Request({
      url: api.logout,
    });
    if (!result) {
      return;
    }
    store.commit("updateLoginUserInfo", null);
  });
};

//获取系统配置
const loadSysSetting = async () => {
  let result = await proxy.Request({
    url: api.getSysSetting,
  });
  if (!result) {
    return;
  }
  store.commit("saveSysSetting", result.data);
};

const goSearch = () => {
  router.push("/search");
};

//是否展示底部
const showFooter = ref(true);
watch(
  () => route.path,
  (newVal, oldVal) => {
    if (newVal.indexOf("newPost") != -1 || newVal.indexOf("editPost") != -1) {
      showFooter.value = false;
    } else {
      showFooter.value = true;
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.header {
    top: 0px;
    position: fixed;
    width: 100%;
    height: 60px;
    // background-color: #91cec9;
    // background-color: #e8f6e9;
    background-color: #5da58a;
    z-index: 1000;
    align-items: center;
    justify-content: center;
    /* 设置页面阴影 */
    box-shadow: 2px 1px 19px rgba(0, 0, 0, .1);
}

.body-content {
    position: relative;
    margin-top: 60px;
    min-height: calc(100vh - 210px);
    // background-color: #ecfcdf;
    background-color: #e8f6e9;
    display: flex;
    justify-content: center;
}

.header-content {
    height: 60px;
    width: 1100px;
    margin: 0px auto;
    // background-color: #549b9d;
    background-color: #5da58a;
    align-items: center;
    display: flex;
    /* 设置页面阴影 */
    box-shadow: 2px 1px 19px rgba(0, 0, 0, .1);
}

.logo {
  display: block;
  /* color: #F5D3B8; */
  color: aliceblue;
  font-family: SimSun;
  font-size: 35px;
  font-weight: bold;
  text-decoration: none;
  margin: 5px;
}

.menu-panel {
    flex: 1;
    font-family: SimSun;
    font-size: 20px;
    font-weight: bold;
    color: #f3d2b5;
    .menu-item {
        margin-left: 20px;
        cursor: pointer;
    }

    .home {
        text-decoration: none;
        color: #000;
    }

    .active {
        color: var(--link);
    }
}

.user-info {
    width: 310px;
    display: flex;
    align-items: center;
    .op-btn {
        .iconfont {
          margin-left: 5px;
        }
        .el-button + .el-button {
          margin-left: 5px;
        }
    }
        .message-info {
            margin-left: 5px;
            margin-right: 25px;
            cursor: pointer;
        .icon-message {
          font-size: 25px;
          color: rgb(147, 147, 147);
        }
    }
}

::v-deep .color-button {
  margin-left: 8px;
  background-color: #f89809;
  font-weight: bold;
}

.admin {
  margin-left: 10px;
}

::v-deep .col {
  color: #eca77a;
  font-weight: bold;
}

.acive-box {
  position: fixed;
  background-color: #eca77a;
}

.sub-board-list {
  display: flex;
  flex-wrap: wrap;
  .sub-board {
    padding: 0px 10px;
    border-radius: 20px;
    margin-right: 10px;
    background: rgb(239, 239, 239);
    border: 1px solid #ddd;
    color: rgb(119, 118, 118);
    margin-top: 10px;
    cursor: pointer;
  }

  .sub-board:hover {
    color: #eca77a;
  }
  .active {
    background: var(--link);
    color: #eca77a;
  }
  .active:hover {
    color: #eca77a;
  }
}

</style>